package cn.comtom.ewbs.signature.service.impl;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.comtom.ewbs.signature.common.vo.dto.SysMenu;
import cn.comtom.ewbs.signature.common.vo.request.PageRequest;
import cn.comtom.ewbs.signature.entity.SysPermission;
import cn.comtom.ewbs.signature.mapper.SysPermissionMapper;
import cn.comtom.ewbs.signature.service.ISysPermissionService;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author liuhy
 * @since 2022-11-04 18:07:24
 */
@Service
@Slf4j
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {
	
	@Autowired
	private SysPermissionMapper sysPermissionMapper;
	
	@Override
	public IPage<SysPermission> selectPage(SysPermission sysPermission, PageRequest pageReq) {
		Page<SysPermission> page = new Page<SysPermission>(pageReq.getPage() , pageReq.getLimit() , true);
        LambdaQueryWrapper<SysPermission> wrapper = Wrappers.lambdaQuery();
        wrapper.setEntity(sysPermission);
        return this.baseMapper.selectPage(page, wrapper);
	}
	
	/**
	 * 递归查询权限
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	public static List<SysMenu> getSysMenus(List<SysPermission> treeList,String parentId){
		List<SysMenu> SysMenuList = new ArrayList<SysMenu>();
		if(StrUtil.isNotBlank(parentId)&&treeList!=null&&treeList.size()>0){
			List<SysMenu> childList=null;
			for (SysPermission tsysPermission : treeList) {
				if(tsysPermission.getPid().equals(parentId)){
					if(tsysPermission.getChildCount()!=null&&tsysPermission.getChildCount()>0){
						childList=getSysMenus(treeList,tsysPermission.getId());
					}
					SysMenu sysMenu=new SysMenu(tsysPermission.getId(), tsysPermission.getPid(), tsysPermission.getName(),tsysPermission.getType(),tsysPermission.getIsBlank(),tsysPermission.getIcon(), tsysPermission.getUrl(), childList);
					SysMenuList.add(sysMenu);
					childList = null;
				}
			}
		}
		return SysMenuList;
	}

	@Override
	public List<SysMenu> getSysMenus(String userId) {
		List<SysPermission> list = null;
		if(StrUtil.isBlank(userId)) {
			LambdaQueryWrapper<SysPermission> wrapper = Wrappers.lambdaQuery();
			wrapper.eq(SysPermission::getVisible, 0);
			list = this.list(wrapper);
		}else {
			list = sysPermissionMapper.findAllByUserId(userId);	
		}
		return getSysMenus(list, "0");
	}
}
